
import numpy as np
import matplotlib.pyplot as plt

def f(x):
    if x >= 0:
        return np.power(x,1.0/3)
    else:
        return - np.power(-x, 1.0/3)

def df(x):
    if x >= 0:
        return 1.0/3 * np.power(x,-2.0/3)
    else:
        return - 1.0/3 * np.power(-x,-2.0/3)

def NewtonSolve(f,df,a,precision):
    x0 = a - 10*precision; x1 = a
    iter = 0
    while(abs(x1-x0)>precision and iter < 10):
        print("x0 = ", x0, "x1 = ", x1)
        x0 = x1
        x1 = x0 - f(x0) / df(x0)
        iter += 1
    return x1, abs(x1-x0), f(x1)

y = NewtonSolve(f,df, 1, 0.01) # 参数：函数、一阶导函数、初值 x = 2、精度要求 error <= 0.1
print("root = ",y[0], ", f(root) = ", y[2])
print("error = ", y[1])